import { createRouter, createWebHashHistory } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import Layout from '@/layout/index.vue'

import homeIcon from './image/home.svg'

const routerConstant: RouterItem[] = [
  {
    path: '/',
    component: Layout,
    redirect: 'home',
    children: [
      {
        path: '/home',
        name: 'home',
        component: () => import('@/views/home/index.vue'),
        meta: {
          title: '首页',
          icon: homeIcon,
          keepAlive: true,
        },
      },
      {
        path: '/overview',
        name: 'overview',
        redirect: 'overview1',
        meta: { title: '总览', icon: '' },
        children: [
          {
            path: '/overview1',
            name: 'overview1',
            component: () => import('@/views/overview/overview1/index.vue'),
            meta: { title: '总览1', keepAlive: true },
          },
          {
            path: '/overview2',
            name: 'overview2',
            component: () => import('@/views/overview/overview2/index.vue'),
            meta: { title: '总览2', keepAlive: false },
          },
        ],
      },
    ],
  },

  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index.vue'),
  },
]

// 路由 对外页面
const routerOut: RouterItem[] = [
  {
    path: '/homeOut',
    name: 'homeOut',
    component: () => import('@/views/home/index.vue'),
  },
]

// 路由 异步请求
const routerAsync: RouterItem[] = []

// 路由 最后加载
const routerLast = [
  {
    path: '/404',
    name: '404',
    component: () => import('@/views/error/404/index.vue'),
  },
  {
    path: '/401',
    name: '401',
    component: () => import('@/views/error/401/index.vue'),
  },

  // 没有匹配到路由，系统跳到404 （注：该路由需要放到最后添加）
  { path: '/:pathMatch(.*)', redirect: '/404', hidden: true },
  // { path: '/:pathMatch(.*)*', redirect: '/404', hidden: true },
]

// 白名单 不需要验证登录
const whiteList = ['/login', '/404', '/401']

// 创建路由
const router = createRouter({
  history: createWebHashHistory(),
  routes: [...routerConstant, ...routerOut, ...routerLast] as any,
})

// 拦截器 路由跳转前
router.beforeEach(async (to, from, next) => {
  NProgress.start()

  // 白名单
  if (whiteList.includes(to.path)) return next()

  // 判断是否登录
  if (await loginFail()) return next('/login')

  next()
})

// 路由跳转后
router.afterEach(() => {
  NProgress.done()
})

// 判断是否登录 先判断token，再调用验证登录接口（接口只调用一次）
let IsLogin = false
async function loginFail() {
  return new Promise((resolve) => {
    if (IsLogin) return resolve(false)

    let { $store, $storeToRefs } = window
    const accessToken = $storeToRefs($store.account).accessToken.value
    if (!accessToken) return resolve(true)

    resolve(false)
  })
}

// 将路由放到vux里
function setRouter(): any {
  let { $store, $storeToRefs } = window
  if (!$store) return setTimeout(() => setRouter(), 500)
  let { routers } = $storeToRefs($store)
  let data = routerConstant.find((item) => item.path == '/')
  routers.value = data?.children
}
setRouter()

// 初始化
function init() {
  window.$router = router
  window.$route = router.currentRoute
}

export default (app: any) => {
  app.use(router)
  init()
}
